home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 14971 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  46 lines

  1. Path: cpsc.ucalgary.ca!davidt
  2. From: davidt@cpsc.ucalgary.ca (David Taylor)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Unions
  5. Date: 2 Apr 1996 22:40:24 GMT
  6. Organization: University of Calgary CPSC
  7. Message-ID: <4jsaco$1pu@linux.cpsc.ucalgary.ca>
  8. References: <rossfeld.1.00111D6B@ucla.edu>
  9. NNTP-Posting-Host: fsj.cpsc.ucalgary.ca
  10. Keywords: Unions
  11.  
  12. In article <rossfeld.1.00111D6B@ucla.edu>,
  13. James E Rossfeld <rossfeld@ucla.edu> wrote:
  14. >Could someone give me a detailed explanation of what the advantages are to 
  15. >using unions (if any).  I'm still a little unfamiliar with how they work.
  16.  
  17. Job security, higher wages... :-)
  18.  
  19. But seriously, unions are just like structs except all the data
  20. elements overlap in memory.  They are useful when you have a structure
  21. or class that has two fields that it never uses together.  For
  22. example, this little class stores either an int or a float:
  23.  
  24. class number {
  25.   private:
  26.     union {
  27.         int int_val;
  28.         float float_val;
  29.     } val;
  30.  
  31.   ...
  32.  
  33. };
  34.  
  35. The benefit of doing this is that the union val will take up
  36. max (sizeof (int), sizeof (float)) instead of sizeof (int) + sizeof
  37. (float).  The disadvantage is that any time int_val is modified,
  38. float_val gets trashed, and vice versa.
  39.  
  40. In many cases, it makes sense to just have a base class, and derive
  41. new subclasses for the shared stuff.  The end result is the same.
  42.  
  43. -- 
  44. Andrew Taylor     |email: davidt@cpsc.ucalgary.ca
  45.                   |www:   http://www.cpsc.ucalgary.ca/~davidt
  46.